/*
 * Copyright 2011 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.social.quickstart.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.appengine.AppEngineUsersConnectionRepository;
import org.springframework.social.connect.support.ConnectionFactoryRegistry;
import org.springframework.social.connect.web.ConnectController;
import org.springframework.social.connect.web.ProviderSignInController;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.impl.FacebookTemplate;
import org.springframework.social.facebook.connect.FacebookConnectionFactory;
import org.springframework.social.quickstart.user.SimpleSignInAdapter;


/**
 * La login.jsp lleva a facebook y te logeas pero luego no me redirige bien a la página de create (register) cargandome lo de facebook.
 * Creo que antes de eso hace un proceso de guardar conexiones en una BD que te montas para la integración de los token.
 * La tengo en JDBC ejemplo, en JPA, pero no en AppEngine. Se la he pasado a Txabi
 * Hay que juntar Socialuser con UserrAccount y luego los metodos de JDBCTemplate
 * Con esos métodos hay que hacer AppEngineUsersConnectionRepository para usarlo en el SocialConfig
 * Hay que añadir al IndexController el bean facebook para que busque algo y lo guarde en Sesisón... lo borre.
 * 
 */

@Configuration
public class SocialConfig {

	@Value("${facebook.clientId}")
	private String facebookClientId;
	
	@Value("${facebook.clientSecret}")
	private String facebookClientSecret;

//    @Bean
//    public ConnectController connectController() {
//        ConnectController controller = new ConnectController(
//            connectionFactoryLocator(), connectionRepository());
//        //controller.setApplicationUrl(environment.getProperty("application.url");
//        return controller;
//    }
    
	@Bean
	@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)	
	public Facebook facebook() {
		ConnectionRepository connectionRepository = connectionRepository();
		Connection<Facebook> facebook = connectionRepository.findPrimaryConnection(Facebook.class);
		return facebook != null ? facebook.getApi() : new FacebookTemplate();
	}
	
	@Bean
	public ConnectionFactoryLocator connectionFactoryLocator() {
		ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();
		registry.addConnectionFactory(new FacebookConnectionFactory(facebookClientId, facebookClientSecret));
		return registry;
	}

	@Bean
	@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)	
	public ConnectionRepository connectionRepository() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null) {
			throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
		}
		UsersConnectionRepository usersConnectionRepository = usersConnectionRepository();
		return usersConnectionRepository.createConnectionRepository(authentication.getName());
	}
	
	// TODO SS RECUPERAR CONEXIONES

	@Bean
	@Scope(value="singleton", proxyMode=ScopedProxyMode.INTERFACES) 
	public UsersConnectionRepository usersConnectionRepository() {
		return new AppEngineUsersConnectionRepository(connectionFactoryLocator(), Encryptors.noOpText());
	}
	
//	@Bean
//	public ProviderSignInController providerSignInController(RequestCache requestCache) {
//		return new ProviderSignInController(connectionFactoryLocator(), usersConnectionRepository(), new SimpleSignInAdapter(requestCache));
//	}	
}